package org.kirhgoff.mathbot;

import java.util.List;


public class Strategy {
	private static long longestIterationTime = 0;
	private final World world;
	private final MathModule module;
	
	public Strategy(World world, MathModule module) {
		this.world = world;
		this.module = module;
	}

	public void doTurn(IssueOrderCallback issueOrderCallback) {
		List<PlanetInfo> myPlanets = world.getMyPlanets ();
		int force = world.myTotalAttackingForce ();
		int index = 0;
		LOGGER.info("STRATEGY DO_TURN available force=" + force);
		
		long theVeryStart = System.currentTimeMillis();
		long cycleStart = System.currentTimeMillis();
		
		while (force > 0 && index < myPlanets.size ()) {
			if (Properties.TURN_LENGTH - System.currentTimeMillis() + theVeryStart <= 2*longestIterationTime) {
				break;
			}
			
			PlanetInfo myPlanet = myPlanets.get(index);
			PlanetInfo target = module.getBestTargetForAttackFrom (world, myPlanet);
			int myPlanetForce = myPlanet.force();
			int planetRequiredForce = module.howMuchIsRequiredToCapture (world, target, myPlanet);
//			if (planetRequiredForce == 0) {
//				continue;
//			}
			
			int shipsToSend = 0;
			if (planetRequiredForce + Properties.DELTA > myPlanetForce) {
				shipsToSend = myPlanetForce;
				index ++;
			}
			else {
				shipsToSend = planetRequiredForce + Properties.DELTA;
			}
			if (shipsToSend != 0) {
				force -= shipsToSend;
				if (planetRequiredForce < shipsToSend) {
					target.setCoveredByAttack (true);
				}
				myPlanet.setForce(myPlanetForce - shipsToSend);
				issueOrderCallback.issueOrder (myPlanet, target, shipsToSend);
			}
			else {
				LOGGER.info("ERROR: Ships to send == 0 planetRequiredForce=" + planetRequiredForce + " myPlanetForce=" + myPlanetForce);
			}
			
			long turnTime = System.currentTimeMillis() - cycleStart;
			LOGGER.info("STRATEGY DO_TURN time=" + turnTime+ " ms");
			if (turnTime > longestIterationTime) {
				longestIterationTime = turnTime;
			}
 			cycleStart = System.currentTimeMillis();
		}
	}

}
